import {Util,I18Parse,CommonLang,TokenUtil} from '@lowcode/jpaas-base-lib';
import useMain from "@/stores/useMain.js";
import { mapState,mapActions} from 'pinia';
import InsPortalDefApi from "@/common/api/portal/insPortalDef.js"
import InsAppCollectApi from "@/common/api/portal/insAppCollect.js"
import dayjs from 'dayjs'
import {getAuthorizeUri, getState} from "@/assets/js/loginPublic.js";
import extendPortal from "./js/extendPortal.js"
import shareFunction from "./js/shareFunction.js"
import InAppAdd from "@/views/modules/portal/core/InAppAdd.vue"

export default {
    mixins: [extendPortal,shareFunction],
    data() {
        return {
            colId: "",
            insColumnDef: {},
            data: [],
            //这个是TAB的组件才使用到
            currentKey: 0,
            loading: false,
            menu:{}
        }
    },
    computed: {
        ...mapState(useMain,['menus','appId','navigations','appKey','curApp']),
    },
    methods: {
        ...mapActions(useMain,['setNavigations','setNavigation']),
        /**
         * 国际化
         */
        i18n(name,text,key){
            return this.$ti18(name,text,"portalApi",key);
        },
        /**
         * 获取图片路径.
         * @param fileId    文件ID
         * @param isScale   是否缩放.
         * @returns {string}
         */
        getImgPath(fileId,isScale) {
            let accessToken =TokenUtil.getToken();
            if(isScale){
                return `/api/api-system/system/core/sysFile/downloadScale/${fileId}?accessToken=` + accessToken;
            }else {
                return `/api/api-system/system/core/sysFile/download/${fileId}?accessToken=` + accessToken;
            }
        },
        changeKey(key) {
            this.currentKey = key;
        },
        /**
         * 平台内部菜单跳转
         * @param insColumnDef 当前栏目
         * @param newWin 新窗口
         */
        moreUrl(insColumnDef,newWin) {
            let url = insColumnDef ? insColumnDef.url :"";
            let name = insColumnDef && insColumnDef.name ? insColumnDef.name : this.insColumnDef.name;
            if (url) {
                if (newWin) {
                    window.open(url);
                } else {
                    this.handUrlClick(url,name);
                }
            } else {
                let typeName = this.insColumnDef.typeName;
                if ("TabBel" === typeName) {
                    insColumnDef =insColumnDef ?insColumnDef : this.data[this.currentKey].insColumnDef;
                    let settingObj = JSON.parse(insColumnDef.setTing);
                    let moreUrl = settingObj.dataUrl;
                    if (moreUrl) {
                        if (newWin) {
                            window.open(moreUrl);
                        } else {
                            this.handUrlClick(moreUrl,name);
                        }
                    }
                } else {
                    insColumnDef =insColumnDef ?insColumnDef : this.insColumnDef;
                    let settingObj = JSON.parse(insColumnDef.setTing);
                    let moreUrl = settingObj.dataUrl;
                    if (moreUrl) {
                        if (newWin) {
                            window.open(moreUrl);
                        } else {
                            this.handUrlClick(moreUrl,name);
                        }
                    }
                }
            }
        },
        /**
         * 刷新数据。
         */
        refresh() {
            let typeName = this.insColumnDef.typeName;
            //当数据是TAB的情况
            if ("TabBel" == typeName) {
                //在tab的容器必须为 innerLayout
                let aryTabs = this.$refs.innerLayout;
                let tab = aryTabs[this.currentKey];
                tab.formVm.loadColumn();
            } else {
                this.loadColumn();
            }
        },
        loadData() {
            this.loading = true;
            //如果appId有值
            if(this.appId){
                InsPortalDefApi.getDataByColIdAndAppId(this.colId,this.appId).then(res => {
                    this.data = res;
                    this.loading = false;
                });
            }else{
                InsPortalDefApi.getDataByColId(this.colId).then(res => {
                    this.data = res;
                    this.loading = false;
                });
            }
        },
        /**
         * 加载栏目数据.
         */
        loadColumn() {
            let type = this.insColumnDef.typeName;
            let typeName = "init_" + type;
            //在特定的扩展中如果有 init_类型的方法，那么就调用该方法。
            if (this[typeName]) {
                this[typeName]();
            }
            //否则根据栏目ID获取数据。
            else {
                this.loadData();
            }
        },
        /**
         * 时间戳转换为日期格式
         * @param timestamp     时间戳 1727411392518
         * @param format        时间格式 YYYY-MM-DD
         * @returns {*|string}
         */
        getDate(timestamp, format) {
            format = format ? format : "YYYY-MM-DD HH:mm:ss";
            if (timestamp) {
                return dayjs(timestamp).format(format);
            }
            return "";
        },
        /**
         * 外部url跳转
         * @param url   外部URL
         */
        moreOutUrl(url){
            if(url){
                window.open(url);
            }
        },
        //常用应用点击
        handAppClick(commonApp){
            //内部应用
            if(commonApp.type ==='interior'){
                if(commonApp.app){
                    let appObj = JSON.parse(commonApp.app);
                    let menu=this.menus.find(item=>item.appId===appObj.value)
                    menu && this.handClick(menu);
                }else {
                    this.moreUrl(commonApp.url, false);
                }
            }else if(commonApp.type === 'outside'){
                let state = getState();
                let clientIdJson=commonApp.clientId;
                let clientId;
                if(clientIdJson){
                    clientId=JSON.parse(clientIdJson).value;
                }
                if(!clientId){
                    return;
                }
                getAuthorizeUri(state,clientId,function(authorizeUri){
                    window.open(authorizeUri);
                });
            }else {
                this.moreOutUrl(commonApp.url);
            }

        },
        //删除应用
        handAppDelete(commonApp){
            let self = this;
            this.$confirm({
                title: this.i18n('msa.delAppInfo','是否删除应用'),
                okText: I18Parse.getI18Val(CommonLang,'rxForm.ackBtn', '确认'),
                cancelText: I18Parse.getI18Val(CommonLang,'rxForm.cancelBtn', '取消'),
                onOk(){
                    InsAppCollectApi.del({ids:commonApp.id}).then(res=>{
                        self.loadData();
                    })

                }
            });
        },
        /**
         * 应用点击.
         * @param item
         */
        handClick(item) {
            //用户开发应用
            if (item.appType === 1) {
                if(item.menuNavType === 1){
                    //新窗口打开
                    let path = item.path?item.path : "/apps";
                    window.open(path + "/" + item.clientCode, '_blank');
                }else {
                    //内置和内置微前端 接收在首页的LayoutMethods.js
                    this.$bus.emit('openApp',item)
                }
                return;
            }
            //外部链接情况
            if (item.layout && item.layout === "external") {
                window.open(item.params, '_blank');
                return;
            }
        },
        /**
         * 处理路由跳转(页签方式)
         * @param url 路径
         * @param title 标题
         */
        handUrlClick(url,title){
            let _url = window.location.href ;
            if(!url) {
                return;
            }
            let urlSplits=url.split("\/");
            let obj = {
                collapsed:true,
                key:urlSplits[1],
                menuKey:urlSplits[1],
                title:title,
                name:title,
                showType:'URL',
            }
            this.setNavigation(obj.menuKey);
            this.setNavigations(Util.deepClone(this.navigations))
            if(this.curApp && this.curApp.isMicroApp){
                let data = {
                    ...obj,
                    microApp:'homeIndex',
                    randomKey:Util.randomId()
                }
                //表示从当前子应用的首页触发的事件
                window.microApp && window.microApp.dispatch(data)
            }
            let path = `${url}` ;
            if(this.appKey || _url.includes('microApp')){
                path = "/"+this.appKey+url ;
            }
            let item = {
                path: path,
                query:{}
            }
            //内置应用时 需要带着appId
            let appId = Util.getUrlParam("appId");
            if(appId){
                item.query.appId = appId;
            }
            //静态路由跳转
            if(path.includes('?')){
                this.$router.push(path).then(() => {
                    window.location.reload()
                })
            }else {
                this.$router.push(item)
            }
        },
        //添加常用应用
        addCommonApp(){
            var self=this;
            Util.open({
                component: InAppAdd,
                curVm: this,
                title: '添加常用应用',
                data:{
                    appType:"custom",
                    appList:this.data,
                    colId:this.colId,
                },
                max:true,
            }, function (action) {
                self.loadData();
            });
        },
        getIcon(item){
            let iconConfig = new Function('return ' +item.icon )();
            return iconConfig.icon;
        },
        getType(item){
            let iconConfig = new Function('return ' +item.icon )();
            return iconConfig.type
        },
    }
}
